package com.jarveis.dbs.core.filter;

import java.sql.SQLException;

import org.apache.log4j.Logger;

import com.jarveis.dbs.core.DBContext;
import com.jarveis.dbs.core.bean.FunctionBean;
import com.jarveis.frame.jdbc.JdbcManager;
import com.jarveis.frame.jdbc.JdbcUtil;
import com.jarveis.frame.util.Param;

/**
 * @desc jdbc过滤器
 * @author liuguojun
 * @create 2016-01-08
 */
public class JdbcFilter implements Filter {

	private Logger logger = Logger.getLogger(JdbcFilter.class);

	public int init() {
		JdbcManager.init();
		logger.info("初始化JDBC成功");
		return 0;
	}

	public int filter(Param param) {

		try {
			String tagName = param.getTagName();

			String funcId = param.getHead().getString(Param.LABEL_FUNCID);
			String errcode = param.getHead().getString(Param.LABEL_ERROR);
			FunctionBean function = DBContext.getInstance().getFunction(funcId);
			if (function != null) {
				Boolean transaction = function.getTransaction(); // 是否开启事务
				if (transaction == null) {
					transaction = false;
				}
				boolean autoCommit = JdbcUtil.getAutoCommit(); // 自动事务

				if (transaction && autoCommit) {
					// 开启事务
					JdbcUtil.startTransaction();
				} else if (transaction && !autoCommit) {
					if (Param.ERROR_SUCCESS.equals(errcode)) {
						// 提交事务
						JdbcUtil.commit();
					} else {
						// 回滚事务
						JdbcUtil.rollback();
					}
				} else if (!transaction && autoCommit) {
					// 不做处理
				} else if (!transaction && !autoCommit) {
					throw new SQLException("数据库事务异常");
				}
			}

			
			if (Param.RESP.equals(tagName)) {
				JdbcManager.closeConnection();
			}

			return 0;
		} catch (SQLException ex) {
			logger.error(ex.getMessage(), ex);
			return Param.ERROR_EXCEPTION;
		}

	}

	public int destory() {
		return 0;
	}
}
